package com.huluobo.a2301mdmdemo.demo

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.content.Context
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.AccelerateInterpolator
import android.widget.ImageView
import android.widget.RelativeLayout
import com.huluobo.a2301mdmdemo.R
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.util.Random
import java.util.Timer
import kotlin.concurrent.timerTask

/**
 *  Created by LC on 2025/7/5.
 */
class RedPackRainView(context: Context) : RelativeLayout(context) {
    //计时器,计算间隔多长时间生成一个红包
    private lateinit var timer: Timer

    fun start() {
        timer = Timer()
        timer.schedule(timerTask {
            //job是个工作对象,也是一个context
            CoroutineScope(Job()).launch(Dispatchers.Main) {
                //创建一个imageView,存放图片
                val iv = ImageView(context)
                //设置图片资源
                iv.setImageResource(R.drawable.liked)
                //设置图片大小
                val params = LayoutParams(100, 100)
                //产生雨点的关键因素,设置随机的左边距
                val num = Random().nextInt(980)
                params.topMargin = 0
                params.leftMargin = num
                //想属性设置到iv上
                iv.layoutParams = params

                val animator = ObjectAnimator.ofFloat(iv, "translationY", 0f, 1920f)
                animator.duration = 1000
                //设置加速插值器
                animator.interpolator = AccelerateInterpolator()
                animator.addListener(object : AnimatorListenerAdapter() {
                    override fun onAnimationEnd(animation: Animator) {
                        super.onAnimationEnd(animation)
                        //当动画结束时,移除掉iv
                        removeView(iv)
                    }
                })
                animator.start()
                addView(iv)
            }
        }, 0, 100)
    }
}